/**
 * 条码库 - 主界面
 * 
 * @author 李静波
 */
Ext.define("PSI.Barcode.MainForm", {
	extend : "Ext.panel.Panel",

	initComponent : function() {
		var me = this;

		Ext.apply(me, {
					border : 0,
					layout : "border",
					tbar : me.getToolbarCmp(),
					items : [{
								region : "north",
								height : 60,
								layout : "fit",
								border : 0,
								title : "查询条件",
								collapsible : true,
								layout : {
									type : "table",
									columns : 5
								},
								items : me.getQueryCmp()
							}, {
								region : "center",
								layout : "border",
								border : 0,
								items : [{
											region : "west",
											width : "40%",
											split : true,
											layout : "fit",
											items : [me.getMainGrid()]
										}, {
											region : "center",
											layout : "fit",
											border : 0,
											items : [me.getDetailGrid()]
										}]
							}]
				});

		me.callParent(arguments);

		me.refreshMainGrid();
	},

	getToolbarCmp : function() {
		var me = this;
		return [{
					text : "新建条码",
					iconCls : "PSI-button-add",
					scope : me,
					handler : me.onAddBarcode
				}, "-", {
					text : "编辑条码",
					id : "buttonEdit",
					iconCls : "PSI-button-edit",
					scope : me,
					handler : me.onEditBarcode
				}, "-", {
					text : "删除条码",
					id : "buttonDelete",
					iconCls : "PSI-button-delete",
					scope : me,
					handler : me.onDeleteBarcode
				}, "-", {
					text : "关闭",
					iconCls : "PSI-button-exit",
					handler : function() {
						location.replace(PSI.Const.BASE_URL);
					}
				}];
	},

	getQueryCmp : function() {
		var me = this;
		return [{
					id : "editQueryBarcode",
					labelWidth : 60,
					labelAlign : "right",
					labelSeparator : "",
					fieldLabel : "条码",
					margin : "5, 0, 0, 0",
					xtype : "textfield"
				}, {
					id : "editQueryGoods",
					xtype : "psi_goodsfield",
					labelAlign : "right",
					labelSeparator : "",
					margin : "5, 0, 0, 0",
					fieldLabel : "商品"
				}, {
					xtype : "container",
					items : [{
								xtype : "button",
								text : "查询",
								width : 90,
								margin : "5 0 0 10",
								iconCls : "PSI-button-refresh",
								handler : me.onQuery,
								scope : me
							}, {
								xtype : "button",
								text : "清空查询条件",
								width : 90,
								margin : "5, 0, 0, 10",
								handler : me.onClearQuery,
								scope : me
							}]
				}];
	},

	getMainGrid : function() {
		var me = this;
		if (me.__mainGrid) {
			return me.__mainGrid;
		}

		var modelName = "PSIBarcode";
		Ext.define(modelName, {
					extend : "Ext.data.Model",
					fields : ["id", "barcode"]
				});
		var store = Ext.create("Ext.data.Store", {
					autoLoad : false,
					model : modelName,
					data : [],
					pageSize : 20,
					proxy : {
						type : "ajax",
						actionMethods : {
							read : "POST"
						},
						url : PSI.Const.BASE_URL + "Home/Barcode/barcodeList",
						reader : {
							root : 'dataList',
							totalProperty : 'totalCount'
						}
					}
				});
		store.on("beforeload", function() {
					store.proxy.extraParams = me.getQueryParam();
				});
		store.on("load", function(e, records, successful) {
					if (successful) {
						me.gotoMainGridRecord(me.__lastId);
					}
				});

		me.__mainGrid = Ext.create("Ext.grid.Panel", {
					title : "条码库",
					viewConfig : {
						enableTextSelection : true
					},
					border : 0,
					columnLines : true,
					columns : [{
								xtype : "rownumberer",
								width : 50
							}, {
								header : "条码",
								dataIndex : "barcode",
								width : 300,
								menuDisabled : true,
								sortable : false
							}],
					listeners : {
						select : {
							fn : me.onMainGridSelect,
							scope : me
						}
					},
					store : store,
					bbar : [{
								id : "pagingToobar",
								xtype : "pagingtoolbar",
								border : 0,
								store : store
							}, "-", {
								xtype : "displayfield",
								value : "每页显示"
							}, {
								id : "comboCountPerPage",
								xtype : "combobox",
								editable : false,
								width : 60,
								store : Ext.create("Ext.data.ArrayStore", {
											fields : ["text"],
											data : [["20"], ["50"], ["100"],
													["300"], ["1000"]]
										}),
								value : 20,
								listeners : {
									change : {
										fn : function() {
											store.pageSize = Ext
													.getCmp("comboCountPerPage")
													.getValue();
											store.currentPage = 1;
											Ext.getCmp("pagingToobar")
													.doRefresh();
										},
										scope : me
									}
								}
							}, {
								xtype : "displayfield",
								value : "条记录"
							}]
				});

		return me.__mainGrid;
	},

	getDetailGrid : function() {
		var me = this;

		if (me.__detailGrid) {
			return me.__detailGrid;
		}

		var modelName = "PSIGoodsBarcode";
		Ext.define(modelName, {
					extend : "Ext.data.Model",
					fields : ["goodsCode", "goodsName", "goodsSpec"]
				});
		var store = Ext.create("Ext.data.Store", {
					autoLoad : false,
					model : modelName,
					data : []
				});

		me.__detailGrid = Ext.create("Ext.grid.Panel", {
					viewConfig : {
						enableTextSelection : true
					},
					title : "使用该条码的商品",
					columnLines : true,
					columns : [{
								header : "商品编码",
								dataIndex : "goodsCode",
								menuDisabled : true,
								sortable : false,
								width : 120
							}, {
								header : "商品名称",
								dataIndex : "goodsName",
								menuDisabled : true,
								sortable : false,
								width : 200
							}, {
								header : "规格型号",
								dataIndex : "goodsSpec",
								menuDisabled : true,
								sortable : false,
								width : 200
							}],
					store : store
				});

		return me.__detailGrid;
	},

	refreshMainGrid : function(id) {
		var me = this;
		
		var gridDetail = me.getDetailGrid();
		gridDetail.setTitle("使用该条码的商品");
		gridDetail.getStore().removeAll();
		Ext.getCmp("pagingToobar").doRefresh();
		me.__lastId = id;
	},

	onAddBarcode : function() {
		var me = this;
		var form = Ext.create("PSI.Barcode.EditForm", {
					parentForm : me
				});
		form.show();
	},

	onEditBarcode : function() {
		var me = this;

		var item = me.getMainGrid().getSelectionModel().getSelection();
		if (item == null || item.length != 1) {
			PSI.MsgBox.showInfo("请选择要编辑的条码");
			return;
		}
		var barcode = item[0];

		var form = Ext.create("PSI.Barcode.EditForm", {
					parentForm : me,
					entity : barcode
				});
		form.show();
	},

	onDeleteBarcode : function() {
		var me = this;
		var item = me.getMainGrid().getSelectionModel().getSelection();
		if (item == null || item.length != 1) {
			PSI.MsgBox.showInfo("请选择要删除的条码");
			return;
		}
		var barcode = item[0];

		var info = "请确认是否删除条码: <span style='color:red'>"
				+ barcode.get("barcode") + "</span>";
		var id = barcode.get("id");

		PSI.MsgBox.confirm(info, function() {
			var el = Ext.getBody();
			el.mask("正在删除中...");
			Ext.Ajax.request({
						url : PSI.Const.BASE_URL + "Home/Barcode/deleteBarcode",
						method : "POST",
						params : {
							id : id
						},
						callback : function(options, success, response) {
							el.unmask();

							if (success) {
								var data = Ext.JSON
										.decode(response.responseText);
								if (data.success) {
									PSI.MsgBox.showInfo("成功完成删除操作", function() {
												me.refreshMainGrid();
											});
								} else {
									PSI.MsgBox.showInfo(data.msg);
								}
							} else {
								PSI.MsgBox.showInfo("网络错误", function() {
											window.location.reload();
										});
							}
						}

					});
		});
	},

	onMainGridSelect : function() {
		var me = this;
		var grid = me.getMainGrid();
		var item = grid.getSelectionModel().getSelection();
		if (item == null || item.length != 1) {
			return;
		}

		me.refreshDetailGrid();
	},

	refreshDetailGrid : function(id) {
		var me = this;
		me.getDetailGrid().setTitle("使用该条码的商品");
		var grid = me.getMainGrid();
		var item = grid.getSelectionModel().getSelection();
		if (item == null || item.length != 1) {
			return;
		}
		var barcode = item[0];
		me.getDetailGrid().setTitle("使用条码 [ " + barcode.get("barcode") + " ] 的商品");
		grid = me.getDetailGrid();
		var el = grid.getEl();
		el.mask(PSI.Const.LOADING);
		Ext.Ajax.request({
					url : PSI.Const.BASE_URL + "Home/Barcode/goodsList",
					params : {
						id : barcode.get("id")
					},
					method : "POST",
					callback : function(options, success, response) {
						var store = grid.getStore();

						store.removeAll();

						if (success) {
							var data = Ext.JSON.decode(response.responseText);
							store.add(data);

							if (store.getCount() > 0) {
								if (id) {
									var r = store.findExact("id", id);
									if (r != -1) {
										grid.getSelectionModel().select(r);
									}
								}
							}
						}

						el.unmask();
					}
				});
	},

	gotoMainGridRecord : function(id) {
		var me = this;
		var grid = me.getMainGrid();
		grid.getSelectionModel().deselectAll();
		var store = grid.getStore();
		if (id) {
			var r = store.findExact("id", id);
			if (r != -1) {
				grid.getSelectionModel().select(r);
			} else {
				grid.getSelectionModel().select(0);
			}
		} else {
			// grid.getSelectionModel().select(0);
		}
	},

	onQuery : function() {
		this.refreshMainGrid();
	},

	onClearQuery : function() {
		var me = this;

		Ext.getCmp("editQueryBarcode").setValue(null);
		Ext.getCmp("editQueryGoods").clearIdValue();

		me.onQuery();
	},

	getQueryParam : function() {
		var me = this;

		var result = {};

		var barcode = Ext.getCmp("editQueryBarcode").getValue();
		if (barcode) {
			result.barcode = barcode;
		}

		var goodsId = Ext.getCmp("editQueryGoods").getIdValue();
		if (goodsId) {
			result.goodsId = goodsId;
		}

		return result;
	}
});